package com.wangyk.user.service.impl;

import com.wangyk.rabbitmqcommon.VO.ResultVO;
import com.wangyk.rabbitmqcommon.model.user.Product;
import com.wangyk.rabbitmqcommon.utils.ResultVOUtils;
import com.wangyk.user.repository.ProductRepository;
import com.wangyk.user.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService
{
    @Autowired
    private ProductRepository productRepository;

    @Override
    public ResultVO saveProduct(Product product)
    {
        productRepository.save(product);
        ResultVO resultVO = new ResultVO();
        resultVO.setData(product);
        return ResultVOUtils.success(resultVO);
    }

    @Override
    public ResultVO deleteNum(Integer productId)
    {
        Product product = productRepository.findByProductId(productId);
        log.info("no Sync:" + product.getNum());
        product.setNum(product.getNum() - 1);
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        productRepository.save(product);
        ResultVO resultVO = new ResultVO();
        resultVO.setData(product);
        return ResultVOUtils.success(resultVO);
    }

    @Override
    public synchronized ResultVO deleteNumSync(Integer productId)
    {
        Product product = productRepository.findByProductId(productId);
        log.info("Sync:" + product.getNum());
        product.setNum(product.getNum() - 1);
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        productRepository.save(product);
        ResultVO resultVO = new ResultVO();
        resultVO.setData(product);
        return ResultVOUtils.success(resultVO);
    }

    @Override
    public ResultVO deleteNumLock(Integer productId)
    {
        synchronized (this)
        {
            Product product = productRepository.findByProductId(productId);
            log.info("Lock:"+product.getNum());
            product.setNum(product.getNum()-1);
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            productRepository.save(product);
            ResultVO resultVO=new ResultVO();
            resultVO.setData(product);
            return ResultVOUtils.success(resultVO);
        }
    }
}
